package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FocusApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.videoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Focus;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-29 14:43
 **/
@Service
public class SmallVideosService {



    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private videoApi videoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;




    /*
    * 查询视频列表(有推荐先查推荐，没有推荐查询数据库所有)
    * */
    public  PageResult findVideos(Integer page, Integer pagesize) {
        //1.从redis中查询推荐的视频id集合
        String rediskey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String  value = (String) redisTemplate.opsForValue().get(rediskey);
        //2.判断是否存在
        List<Video> list = new ArrayList<>();
        if(!StringUtils.isEmpty(value)){
            //2.1如果存在，获取视频id集合
            String[] vids = value.split(",");
            list =  videoApi.findByIds(vids,page,pagesize);
        }else {
            //2.2如果不存在，查询所有视频
            list = videoApi.findAll(page,pagesize);
        }
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }

        //一次性查询获取所有的视频发布人信息
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

        //3.将一个video转化成一个videoVo
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            //视频发布人的信息
            Long userId = video.getUserId();
            UserInfo us = map.get(userId);
            VideoVo vo = VideoVo.init(us, video);
            vos.add(vo);
        }
        //4.返回
        return  new PageResult(page,pagesize,0L,vos);
    }



    /*
     * 发布视频:
     *      1.文件存储到服务上
            2.保存到数据库表中
     *
     * */
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、封面图上传到阿里云oss
        String picUrl = ossTemplate.upload(videoThumbnail.getInputStream(), videoThumbnail.getOriginalFilename());
        //2.视频上传到fastdfs
        String filename = videoFile.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        filename = filename.substring(index+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);//文件输入流，文件大小，后缀名，元数据
        //拼接url
        String videoUrl = webServer.getWebServerUrl() +storePath.getFullPath();
        //3.构造video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setCreated(System.currentTimeMillis());
        video.setText("我就是我");
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        //4.调用API保存
        videoApi.save(video);
    }


    @Autowired
    private MqMessageService mqMessageService;
    /*
    * 视频点赞*/
    public void like(String videoId) {
        Long userId = UserHolder.getUserId();
        //完成点赞业务逻辑
        //发送日志消息
        mqMessageService.sendLogMessage(userId,"0302","log.video",videoId);
    }

    //取消视频点赞
    public Integer disLikeVideo(String videoId) {

        Long userId = UserHolder.getUserId();
        Integer num = videoApi.disLike(videoId, userId);

        String key = Constants.VIDEO_INTERACT_KEY + videoId;
        String hKey = Constants.VIDEO_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hKey);

        return num;
    }

    //保存视频评论
    public Integer videoSaveComments(String videoId, String txt) {

        return videoApi.videoCommentHandle(videoId, UserHolder.getUserId(), 2, txt);
    }

    //查看视频评论
    public PageResult findVideoComments(Integer page, Integer pageSize, String videoId) {
        //获取评论总数和分页过评论详情
        Map map = videoApi.findVideoComments(page, pageSize, videoId);
        System.out.println("获取到的评论集合与总数" + map.toString());

        List<Comment> list = (List<Comment>) map.get("list");
        Long count = (Long) map.get("count");
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        Map<Long, UserInfo> userInfos = userInfoApi.findByIds(userIds);

        List<CommentVo> vos = new ArrayList<>();
        for (Comment videoComment : list) {
            CommentVo vo = CommentVo.init(userInfos.get(videoComment.getUserId()), videoComment);
            vos.add(vo);
        }

        return new PageResult(page, pageSize, count, vos);
    }


    @DubboReference
    private FocusApi focusApi;
    public void focus(String toUserId) {
        Long userId = UserHolder.getUserId();
        Focus focus = new Focus();
        focus.setCreated(System.currentTimeMillis());
        focus.setUserId(userId);
        focus.setToUserId(Long.parseLong(toUserId));

        focusApi.focus(focus);
    }

    public void unFocus(String toUserId) {
        Long userId = UserHolder.getUserId();
        focusApi.unFocus(userId, Long.parseLong(toUserId));
    }
/*
    public static void main(String[] args) {
        String filename = "zzzz.xxxx.mp4";
        int index = filename.lastIndexOf(".");
        filename = filename.substring(index+1);
        System.out.println(filename);

    }*/
}
